const { Controller } = require('egg');

class BaseController extends Controller {
  get user() {
    return this.ctx.user ? this.ctx.user : {};
  }

  async get() {
    const { ctx, app } = this;
    if(!ctx.query.id){
      return ctx.fail('需要传id');
    }
    const rs = await app.mysql.get(this.tableName, { id: ctx.query.id });
    return rs && rs.id > 0 ? ctx.success(ctx.helper.toPlainObject(rs)) : ctx.fail('找不到这个ID相关的数据');
  }

  async select() {
    const { ctx, app } = this;
    let { key = '' } = ctx.query;
    const list = await app.mysql.query(`select * from ${this.tableName} where delete_time is null and name like "%${key}%" order by create_time desc`);
    return list ? ctx.success(list) : ctx.fail('查询数据失败');
  }

  async page() {
    const { ctx, app } = this;
    let { currentPage = 1, pageSize = 2, key = '' } = ctx.query;
    currentPage = parseInt(currentPage);
    pageSize = parseInt(pageSize);
    const all = await app.mysql.query(`select * from ${this.tableName} where delete_time is null and name like "%${key}%"`);
    const list = await app.mysql.query(`select * from ${this.tableName} where delete_time is null and name like "%${key}%" order by create_time desc limit ${(currentPage - 1) * pageSize}, ${pageSize}`);
    const count = all.length;
    const total = Math.ceil(count / pageSize);
    return list ? ctx.success({ currentPage, total, count, list }) : ctx.fail('查询分页失败');
  }

  async insert() {
    const { ctx, app } = this;
    const rs = await app.mysql.insert(this.tableName, { ...ctx.request.body, create_time: Date.now() });
    return rs.insertId > 0 ? ctx.success(rs.insertId) : ctx.fail('新增失败');
  }

  async update() {
    const { ctx, app } = this;
    if(ctx.request.body.id){
      ctx.request.body.id = parseInt(ctx.request.body.id);
    }else{
      return ctx.fail('需要传id');
    }
    const rs = await app.mysql.update(this.tableName, ctx.request.body);
    return rs.affectedRows > 0 ? ctx.success() : ctx.fail('更新失败');
  }

  async trash() {
    const { ctx, app } = this;
    if(ctx.request.body.id){
      ctx.request.body.id = parseInt(ctx.request.body.id);
    }else{
      return ctx.fail('需要传id');
    }
    const rs = await app.mysql.update(this.tableName, { delete_time: Date.now(), id:ctx.request.body.id });
    return rs ? ctx.success() : ctx.fail('删除失败');
  }

  async delete() {
    const { ctx, app } = this;
    if(ctx.request.body.id){
      ctx.request.body.id = parseInt(ctx.request.body.id);
    }else{
      return ctx.fail('需要传id');
    }
    const rs = await app.mysql.delete(this.tableName, ctx.request.body);
    return rs ? ctx.success() : ctx.fail('删除失败');
  }

}

module.exports = BaseController;